package com.codingday.app;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SaveManager {


	private static final String DATABASE_NAME= "geoalarm.db";
	private static final int DATABASE_VERSION = 7;
	
	private static final String QUEST_TABLE_NAME = "TODOs";
	private static final String PLACE_TABLE_NAME = "PLACEs";
	
	private static DBManager dbmanager=null;
	private static Context ctx;
	
	static SaveManager svm = null;
	
	public SaveManager(){
		if(dbmanager == null){
			if(ctx == null){
				ctx = GeoAlarmService.getInstance();
			}
			if(ctx != null){
				dbmanager = new DBManager(ctx,DATABASE_NAME,null,DATABASE_VERSION);
			}
		}
	}
	
	
	public static boolean DeleteTODO(long id){
		boolean result = true;
		//long id = todo.getID();
		SQLiteDatabase db = dbmanager.getWritableDatabase();
		try{
			Log.i("SaveManger","Try to Delete ... "+ id);
			int row = db.delete(QUEST_TABLE_NAME, "_id="+id, null);
			Log.i("SaveManger","Delete " + row + " rows");
		}catch(Exception e){
			Log.i("SaveManager","delete failed");
			result = false;
		}
		return result;
	}
	
	public synchronized static boolean updateTODO(TODO todo){
		boolean result = true;
		if(svm == null){
			svm = new SaveManager();
		}

		SQLiteDatabase db = dbmanager.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		
		//values.put("FINISHED", 1);
		//values.put("DATE_FINISHED",dateFormat.format(date));
		//Log.i("SaveTODO",todo.getTitle());
		//Log.i("SaveTODO",todo.getDesc());
		values.put("TITLE", todo.getTitle());
		values.put("ENABLED", (todo.isEnabled()==true)?1:0);
		values.put("PAUSED", (todo.isPausedByInitial()==true)?1:0);
		values.put("DATE_CREATED",dateFormat.format(date));
		todo.setCreatedDate(date);		// date modified
		values.put("DESC", todo.getDesc());
		if(todo.getCompletedDate() == null){
			values.put("DATE_FINISHED", "");
		}
		values.put("LATITUDE", todo.getLatitude());
		values.put("LONGITUDE", todo.getLongitude());
		values.put("RADIUS", todo.getRadius());
		values.put("FINISHED", (todo.isCompleted()==true)?1:0);
		
		long id = todo.getID();
		int rows = db.update(QUEST_TABLE_NAME, values, "_id="+id, null);
		
		if(rows!=1){
			Log.i("SaveManager","Update Failed");
		}else{
			Log.i("SaveManager","Update Success");
		}
		db.close();
		return result;
	}
	
	public synchronized static boolean FinishTODO(TODO todo){
		boolean result = true;
		
		if(svm == null){
			svm = new SaveManager();
		}
		
		SQLiteDatabase db = dbmanager.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		
		values.put("ENABLED",0);
		//values.put("PAUSED", 1);
		values.put("FINISHED", 1);
		values.put("DATE_FINISHED",dateFormat.format(date));
		
		
		long id = todo.getID();
		int rows = db.update(QUEST_TABLE_NAME, values, "_id="+id, null);
		todo.setCompletedDate(date);
		
		if(rows!=1){
			Log.i("SaveManager","Finish Update Failed");
		}else{
			Log.i("SaveManager","Finish Update Success");
		}
		db.close();
		return result;
	}
	
	public synchronized static boolean SaveTODO(TODO todo){
		
		boolean result = true;
		if(svm == null){
			svm = new SaveManager();
		}
		
		//
		SQLiteDatabase db = dbmanager.getWritableDatabase();
		ContentValues values = new ContentValues();
		Log.i("SaveTODO",todo.getTitle());
		Log.i("SaveTODO",todo.getDesc());
		values.put("TITLE", todo.getTitle());
		values.put("ENABLED", (todo.isEnabled()==true)?1:0);
		values.put("PAUSED", (todo.isPausedByInitial()==true)?1:0);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		values.put("DATE_CREATED",dateFormat.format(date));
		todo.setCreatedDate(date);	
		values.put("DESC", todo.getDesc());
		values.put("LATITUDE", todo.getLatitude());
		values.put("LONGITUDE", todo.getLongitude());
		values.put("RADIUS", todo.getRadius());
		values.put("FINISHED", 0);
		values.put("DATE_FINISHED", "");

		Log.i("SaveTODO","latitude : "+todo.getLatitude()+", longitude : "+todo.getLongitude());
		
		try{
			long id = db.insertOrThrow(QUEST_TABLE_NAME, null, values);
			todo.setID(id);
		}catch(Exception e){
			Log.i("error:",e.toString());
			Log.i("SaveManager","insert failed");
			result = false;
		}
		db.close();
		Log.i("SaveManager","Saved");
		return result;
	}
	
	public synchronized static ArrayList<TODO> LoadAllTODO(){
		
		Log.i("SaveManager","LoadAllTODO");
		
		ArrayList<TODO> todolist = new ArrayList<TODO>();
		
		if(svm == null){
			svm = new SaveManager();
		}
		SQLiteDatabase db = dbmanager.getReadableDatabase();
		Cursor cursor = db.query(QUEST_TABLE_NAME, null, null, null, null, null, null);
		Log.i("cursor num:",""+cursor.getCount());
		int i = 0;
		while(cursor.moveToNext()){

			long id = cursor.getLong(0);
			String title = cursor.getString(1).toString();
			boolean enabled = (cursor.getInt(2)==1)?true:false;
			boolean paused = (cursor.getInt(3)==1)?true:false;
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date createdDate;
			try {
				createdDate = dateFormat.parse(cursor.getString(4));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				Log.i("","Date Conversion error");
				createdDate = new Date();
				e.printStackTrace();
			}
			String desc = cursor.getString(5).toString();
			double latitude = cursor.getDouble(6);
			double longitude = cursor.getDouble(7);
			int radius = cursor.getInt(8);
			boolean completed = (cursor.getInt(9)==1)?true:false;
			Date completedDate = null;
			if(completed){
				try {
					completedDate = dateFormat.parse(cursor.getString(10));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					Log.i("","Date Conversion error");
					completedDate = new Date();
					e.printStackTrace();
				}
			}
			
			//Log.i("LoadAll","latitude : "+latitude+", longitude :"+longitude);
			TODO todo = new TODO(title, desc);
			
			todo.setLocation(latitude, longitude,radius);
			todo.setID(id);
			todo.setCreatedDate(createdDate);

			if(completed){
				todo.setCompletedDate(completedDate);
			}
			
			todo.setStatusFromDB(enabled, paused, completed);
			
			todolist.add(todo);
			Log.i("LoadAll","("+i+") " + todo.getTitle()+" ID : "+todo.getID());
			i++;
		}
		cursor.close();
		return todolist;
	}
	
	
	private class DBManager extends SQLiteOpenHelper{


		public DBManager(Context context, String name, CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL("CREATE TABLE " + QUEST_TABLE_NAME 
					+ "( _id INTEGER PRIMARY KEY AUTOINCREMENT, "	/*0*/
					+ "TITLE TEXT NOT NULL, "	/*1*/
					+ "ENABLED INTEGER, "	/*2*/
					+ "PAUSED INTEGER, "		/*3*/
					+ "DATE_CREATED TEXT, "	/*4*/
					+ "DESC TEXT, " 	/*5*/
					+ "LATITUDE INTEGER, "	/*6*/
					+ "LONGITUDE INTEGER, "	/*7*/
					+ "RADIUS INTEGER,"	/*8*/
					+ "FINISHED INTEGER," /*9*/
					+ "DATE_FINISHED TEXT" /* 10 */
					+		");");
			
			db.execSQL("CREATE TABLE " + PLACE_TABLE_NAME 
					+ "( _id INTEGER PRIMARY KEY AUTOINCREMENT, "
					+ "TITLE TEXT NOT NULL, "
					+ "LATITUDE INTEGER,"
					+ "LONGITUDE INTEGER,"
					+ "RADIUS INTEGER"
					+		");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			db.execSQL("DROP TABLE IF EXISTS "+ QUEST_TABLE_NAME );
			db.execSQL("DROP TABLE IF EXISTS "+ PLACE_TABLE_NAME );
			onCreate(db);
		}
		
	}
}
